# -*- coding: utf-8 -*-
from __future__ import unicode_literals

import json

from django.contrib.auth import authenticate, logout
from django.http import JsonResponse
from django.shortcuts import render, HttpResponse

from app import models


# Create your views here.


def index(request):
    return render(request, 'index.html')


def userLogin(request):
    if request.method == 'GET':
        return render(request, 'login.html', {"username": request.user.username})
    else:
        form = json.loads(request.body)
        username = form['username']
        password = form['password']
        print(username, password)
        user = authenticate(username=username, password=password)
        if user:
            return JsonResponse({'code': '20000', 'message': u'登录成功'})
        else:
            return JsonResponse({'code': '30000', 'message': u'用户密码错误'})


def userlogout(request):
    logout(request)
    return HttpResponse('用户注销成功')


from rest_framework_jwt.serializers import JSONWebTokenSerializer
from rest_framework_jwt.views import JSONWebTokenAPIView
from .renderers import APIRenderer
from rest_framework.decorators import api_view, renderer_classes
from rest_framework.response import Response


class LoginTokenAPI(JSONWebTokenAPIView):
    serializer_class = JSONWebTokenSerializer
    renderer_classes = (APIRenderer,)


@api_view(['GET'])
@renderer_classes((APIRenderer,))
def userinfo(request):
    return Response({
        'role': ['admin'] if request.user.is_superuser else ['user'],
        'token': ['admin'] if request.user.is_superuser else ['user'],
        'avatar': 'https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif',
        'name': request.user.last_name
    })


from app import serializers
from rest_framework import viewsets

class hostAPI(viewsets.ModelViewSet):
    queryset = models.Service.objects.all()
    serializer_class = serializers.serviceSerializer



class ketAPI(viewsets.ModelViewSet):
    queryset = models.Key.objects.all()
    serializer_class = serializers.KeySerializer

    def perform_create(self, serializer):
        serializer.save(createUser=self.request.user)

    def perform_update(self, serializer):
        serializer.save(ChangeUser=self.request.user)